﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using TEL.WinMediaWPF.Audio.Wav;

namespace TEL.WinMediaWPF.Audio
{
    public class AnswerMashiceContent
    {
        private bool m_IsDisposed = false;
        private Stream m_pSource = null;
        private WAVFile m_pWavFile = null;

       public AnswerMashiceContent ( Stream source)
       {
           try
           {
               if (source == null)
                   throw new ArgumentNullException("stream");
               m_pSource = source;

               StartSaving(@"AnswerMashiceContent.wav");
               Thread tr = new Thread(this.SendAudio);
               tr.Start();
           }
           catch (Exception)
           {
           }
       }

        /// <summary>
        /// Начинаем запись в <b>WAV</b> фаил
        /// </summary>
        /// <param name="fileName">Имя нового фаила </param>
        public void StartSaving(string fileName)
        {
            if (File.Exists(fileName)) File.Delete(fileName);

            m_pWavFile = new WAVFile();
            m_pWavFile.Create(fileName, false, 8000, 16);
            // m_pWavFile.Create(fileName, false, 11025, 8);
        }

        /// <summary>
        /// Закрытия фаила
        /// </summary>
        public void StopSaving()
        {
            if (m_pWavFile != null)
            {
                m_pWavFile.Close();
                m_pWavFile = null;
            }
        }

        void ReseiverToWav(byte[] content)
        {
            if (m_pWavFile == null) return;
            MemoryStream stream = new MemoryStream(content);
            //int bits = m_pWavFile.BitsPerSample / 8;
            //int r = bits;
            //byte[] bytes = new byte[bits];
            //while (r > 0)
            //{
            //    r = stream.Read(bytes, 0, bits);

            //    m_pWavFile.AddSample_ByteArray(bytes);
            //}
            m_pWavFile.AddSample_ByteArray(stream);

        }

        #region method Dispose

        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public void Dispose()
        {
            if (m_IsDisposed)
            {
                return;
            }
            StopSaving();
            m_IsDisposed = true;
        }

        #endregion
        private void SendAudio()
        {
            int ptime = 20;
            byte[] readBuffer = new byte[320];
            
            while (!m_IsDisposed)
            {
                try
                {
                    if (m_pSource != null)
                    {
                        int readedCount = m_pSource.Read(readBuffer, 0, readBuffer.Length);
                        if (readedCount == 0)
                        {
                            Thread.Sleep(1);

                            continue;
                        }
                        if (m_pWavFile != null) ReseiverToWav(readBuffer);
                        Thread.Sleep(ptime);
                    }
                }
                catch (ObjectDisposedException x)
                {
                    string dummy = x.Message;

                    // RTP session disposed, dispose sender.
                    Dispose();

                    return;
                }
                catch
                {
                }
            }
        }

        public Stream Source
        {
            get
            {
                if (m_IsDisposed)
                {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                return m_pSource;
            }

            set
            {
                if (m_IsDisposed)
                {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                m_pSource = value;
            }
        }
    }
}